/**
 * 向服务器发送token
 */
$(document).ajaxSend(function(e, xhr){
    let token = localStorage.getItem("user_token");
    xhr.setRequestHeader("user_token_header", token);
});
/**
 * 切换聊天/好友列表
 */
function initSwitchTab() {
    // 1.先获取到相关的元素(标签页的按钮, 会话列表, 好友列表)
    let tabSession = document.querySelector('.tab .tab-session');
    let tabFriend = document.querySelector('.tab .tab-friend');
    // querySelectorAll 可以同时选中多个元素. 得到的结果是个数组
    // [0]就是会话列表
    // [1]就是好友列表
    let lists = document.querySelectorAll('.list');
    // 2. 针对标签页按钮, 注册点击事件.
    tabSession.onclick = function() {
        // a)设置图标
        tabSession.style.backgroundImage = 'url(img/session.-selected.png)';
        tabFriend.style.backgroundImage = 'url(img/user.png)';
        // b)让会话列表显示出来, 让好友列表进行隐藏
        lists[0].classList = 'list';
        lists[1].classList = 'list hide';
    }
    tabFriend.onclick = function() {
        // a) 设置图标
        tabSession.style.backgroundImage = 'url(img/session.png)';
        tabFriend.style.backgroundImage = 'url(img/user-selected.png)'
        // b) 让好友列表显示, 让会话列表隐藏
        lists[0].classList = 'list hide';
        lists[1].classList = 'list';
    }
}
initSwitchTab();

let token = localStorage.getItem("user_token");
let webSocket = new WebSocket('ws://127.0.0.1:2006/chat');
webSocket.onopen = function() {
    console.log('建立连接');
    webSocket.send(JSON.stringify({
        type: 'auth',
        token: token
    }));
}
webSocket.onmessage =  function(e) {
    console.log("接收到消息: " + e.data);
    //转换为js对象
    let request = JSON.parse(e.data);
    if (request.type === 'message') {
        handleMessage(request);
    }else {
        console.log("request.type不符合要求");
    }
}
function handleMessage(request){
    //1.根据request.sessionId查找li标签
    let curSessionLi = findSessionLi(request.sessionId);
    if (curSessionLi === null) {
        curSessionLi = document.createElement('li');
        curSessionLi.setAttribute('sessionInfo.sessionId', request.sessionId);
        curSessionLi.innerHTML = '<h3>' + request.fromName + '</h3><p></p>'
        curSessionLi.onclick = function() {
            clickSession(curSessionLi);
        }
    }
    //2.把新的消息显示到预览区域
    let p = curSessionLi.querySelector('p');
    p.innerHTML = request.message;
    if (p.innerHTML.length > 10) {
        p.innerHTML = p.innerHTML.substring(0, 10) + '...';
    }
    //3.将收到消息的会话置顶
    let sessionList = document.querySelector('#session-list');
    sessionList.insertBefore(curSessionLi,sessionList.children[0]);
    //4.如果当前会话处于选中状态,调整滚动条
    if (curSessionLi.className === 'selected') {
        let contentDiv = document.querySelector('.right .message-show');
        addMessage(request,contentDiv);
        scrollBottom(contentDiv);
    }
}
function findSessionLi(targetSessionId){
    let sessionLiList = document.querySelectorAll('#session-list li');
    for (let li of sessionLiList){
        let curSessionId = li.getAttribute('sessionInfo.sessionId');
        if (curSessionId == targetSessionId) {
            return li;
        }
    }
    return null;
}
/**
 * 消息发送/接收
 */
function initSendButton() {
    let sendButton = document.querySelector('.ctrl');
    let messageInput = document.querySelector('.right .message-input');
    sendButton.onclick = function() {
        let content = messageInput.value;
        //判断输入框是否为空
        if (content === '' || content === null) {
            return;
        }
        let selectedLi = document.querySelector('#session-list .selected');
        //判断是否有会话被选中
        if (selectedLi === null) {
            return;
        }
        let sessionId = selectedLi.getAttribute('sessionInfo.sessionId');
        let request = {
            type: 'message',
            sessionId: sessionId,
            content: content,
        }
        request = JSON.stringify(request);
        webSocket.send(request);
        //清空输入框
        messageInput.value = '';
    }
}
initSendButton();
/**
 * 获取登录用户信息
 */
function getUserInfo() {
    $.ajax({
        type: 'get',
        url: 'user/getLoginUser',
        success: function(result) {
            if (result.status === "SUCCESS" && result.data != null) {
                let userDiv = document.querySelector('.main .left .user');
                userDiv.innerHTML = result.data.userName;
            } else {
                alert("当前用户未登录!");
                location.href = "/login.html";
            }
        }
    });
}
getUserInfo();
/**
 * 获取好友列表
 */
function getFriendList(){
    $.ajax({
        url: 'friend/getFriendList',
        type: 'get',
        success: function(result) {
            if (result.status === "SUCCESS") {
                //1.清空好友列表
                let friendList = document.querySelector('#friend-list');
                friendList.innerHTML = '';
                //2.填充服务器数据
                for (let friendInfo of result.data) {
                    let li = document.createElement("li");
                    li.innerHTML = `<h4>${friendInfo.friendName}</h4>`;
                    li.setAttribute('friendInfo.friendId', friendInfo.friendId);
                    friendList.appendChild(li);
                    let friendName = friendInfo.friendName;
                    let friendId = friendInfo.friendId;
                    li.onclick = function() {
                        clickFriend(friendName,friendId);
                    }
                }
            }else {
                alert('当前用户不存在');
                location.href = "/login.html";
            }
        },
        error: function() {
            alert('获取好友列表失败');
        }
    })
}
getFriendList();
/**
 * 点击好友列表
 */
function clickFriend(friendName, friendId) {
    //1.查找会话
    let sessionLi = findSessionByName(friendName);
    let sessionList = document.querySelector('#session-list');
    if (sessionLi !== null) {
        sessionList.insertBefore(sessionLi,sessionList.children[0]);
        //执行注册的函数clickSession()
        sessionLi.click();
    }else {
        //2.创建会话
        let newSessionLi = document.createElement('li');
        newSessionLi.innerHTML = '<h3>' + friendName + '</h3><p></p>';
        sessionList.insertBefore(newSessionLi,sessionList.children[0]);
        //注册函数
        newSessionLi.onclick = function (){
            clickSession(newSessionLi);
        }
        newSessionLi.click();
        createSession(friendId,newSessionLi);
    }
    //3.跳转到会话列表
    let tabSession = document.querySelector('.tab .tab-session');
    tabSession.click();
}
function findSessionByName(friendName) {
    let sessionList = document.querySelectorAll('#session-list>li');
    for (let curLi of sessionList) {
        let h3 = curLi.querySelector('h3');
        if (h3.innerHTML === friendName) {
            return curLi;
        }
    }
    return null;
}
function createSession(friendId,sessionLi) {
    $.ajax({
        type: 'get',
        url: 'message/createSession',
        data: {
            toUserId: friendId,
        },
        success: function(result) {
            if (result.status === "SUCCESS") {
                sessionLi.setAttribute("sessionInfo.sessionId", result.data.sessionId);
                alert('创建会话成功');
            }else {
                alert(result.error);
            }
        },
        error: function() {
            alert('创建会话失败');
        }
    })
}
/**
 * 获取会话列表
 */
function getSessionList(){
    $.ajax({
        url: 'message/getSessionList',
        type: 'get',
        success: function(result) {
            if (result.status === "SUCCESS") {
                let sessionList = document.querySelector('#session-list');
                sessionList.innerHTML = '';
                let messageSessionList = result.data;
                for (let sessionInfo of messageSessionList) {
                    if(sessionInfo.lastMessage.length > 10){
                        sessionInfo.lastMessage = sessionInfo.lastMessage.substring(0, 10) + '...';
                    }
                    let li = document.createElement("li");
                    li.setAttribute('sessionInfo.sessionId', sessionInfo.sessionId);
                    li.innerHTML = `<h3>${sessionInfo.friends[0].friendName}</h3><p>${sessionInfo.lastMessage}</p>`;
                    sessionList.appendChild(li);
                    li.onclick = function() {
                        clickSession(li);
                    }
                }
            }
        }
    })
}
getSessionList();
/**
 * 点击会话列表
 */
function clickSession(currentLi){
    //1.高亮设置
    let liList = document.querySelectorAll('#session-list>li');
    activeSession(liList,currentLi);
    //2.获取历史消息
    let sessionId = currentLi.getAttribute('sessionInfo.sessionId');
    getHistoryMessage(sessionId);
}
function activeSession(liList,currentLi){
    for (let li of liList) {
        if (li === currentLi) {
            li.className = 'selected';
        }else {
            li.className = '';
        }
    }
}
function getHistoryMessage(sessionId) {
    //1.清空已有内容
    let title = document.querySelector('.right .title');
    title.innerText = '';
    let contentDiv = document.querySelector('.right .message-show');
    contentDiv.innerText = '';
    //2.重新设置标题
    let selectedH3 = document.querySelector('#session-list .selected>h3');
    if (selectedH3 !== null) {
        title.innerHTML = selectedH3.innerHTML;
    }
    $.ajax({
        type: 'get',
        url: 'content/getMessageBySessionId',
        data: {
            sessionId: sessionId,
        },
        success: function(result) {
            if (result.status === "SUCCESS") {
                let messageList = result.data;
                for (let message of messageList) {
                    addMessage(message,contentDiv);
                }
                scrollBottom(contentDiv);
            }
        }
    })
}
function addMessage(message,contentDiv) {
    let messageDiv = document.createElement('div');
    let loginUserName = document.querySelector('.left .user').innerHTML;
    if (loginUserName === message.fromName){
        messageDiv.className = 'message message-right';
    }else {
        messageDiv.className = 'message message-left';
    }
    messageDiv.innerHTML = '<div class="box"><h4>' + message.fromName + '</h4><p>' + message.content + '</p></div>';
    contentDiv.appendChild(messageDiv);
}
//设置滚动条
function scrollBottom(element) {
    let clientHeight = element.offsetHeight;
    let scrollHeight = element.scrollHeight;
    element.scrollTo(0,scrollHeight - clientHeight);
}